<template>
  <div>
    <div class="flex justify-between items-center" style="margin: px">
      <div>料仓纸皮剩余情况</div>
      <el-button type="warning" @click="showFormDialogCorrect"
        >纠正纸皮库存</el-button
      >
      <el-button type="primary" @click="showFormDialogAdd"
        >添加纸皮库存</el-button
      >
    </div>

    <div ref="target" class="w-full h-full"></div>
    <el-dialog title="添加纸皮库存" v-model="dialogVisibleAdd" width="30%">
      <el-form label-position="right" label-width="100px">
        <el-form-item label="客户名">
          <el-input v-model="name"></el-input>
        </el-form-item>
        <el-form-item label="幅宽">
          <el-input v-model="width"></el-input>
        </el-form-item>
        <el-form-item label="托数">
          <el-input v-model="length"></el-input>
        </el-form-item>
        <el-form-item label="每托的张数">
          <el-input v-model="sheet"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisibleAdd = false">取 消</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="添加纸皮库存" v-model="dialogVisibleCorrect" width="30%">
      <el-form label-position="right" label-width="100px">
        <el-form-item label="客户名">
          <el-input v-model="name"></el-input>
        </el-form-item>
        <el-form-item label="幅宽">
          <el-input v-model="width"></el-input>
        </el-form-item>
        <el-form-item label="托数">
          <el-input v-model="length"></el-input>
        </el-form-item>
        <el-form-item label="每托的张数">
          <el-input v-model="sheet"></el-input>
        </el-form-item>
        <el-form-item label="剩余的张数">
          <el-input v-model="sheetRemind"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisibleCorrect = false">取 消</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import * as echarts from "echarts";
import {
  getStockByNameApi,
  resetStockTime2Api,
  CorrectStockApi,
} from "../api/packaging.js";
import {
  ElButton,
  ElDialog,
  ElFormItem,
  ElInput,
  ElMessageBox,
  ElMessage,
} from "element-plus";

const props = defineProps({
  data: {
    type: Object,
    required: true,
  },
});

// 获取 dom 实例
const target = ref(null);

// echarts 实例变量
let mChart = null;
// 在 mounted 生命周期之后，实例化 echarts
onMounted(() => {
  mChart = echarts.init(target.value);
  // 渲染 echarts
  renderChart();
});

// 渲染图表
const renderChart = () => {
  const options = {
    // X 轴展示数据
    xAxis: {
      // 数据展示
      type: "value",
      // 不显示轴
      show: false,
      // 最大值（防止触顶）
      max: function (value) {
        // 取整
        return parseInt(115);
      },
    },
    // Y 轴展示选项
    yAxis: {
      type: "category",
      // 根据根据服务端数据筛选
      data: props.data.stockData.map((item) => item.StockName),
      // 反向展示
      inverse: true,
      // 不展示轴线
      axisLine: {
        show: false,
      },
      // 不展示刻度
      axisTick: {
        show: false, // 取消 Y 轴刻度
      },
      // 文字色值
      axisLabel: {
        color: "#9EB1C8",
      },
    },
    // echarts 网格绘制的位置，对应 上、右、下、左
    grid: {
      top: 0,
      right: 0,
      bottom: 0,
      left: 0,
      // 计算边距时，包含标签
      containLabel: true,
    },
    // 柱形图核心配置
    series: [
      {
        // 图表类型
        type: "bar",
        // 数据筛选
        data: props.data.stockData.map((item) => ({
          name: item.StockName,
          value: (item.Percent * 100).toFixed(1),
        })),
        // 显示背景
        showBackground: true,
        // 背景色
        backgroundStyle: {
          color: "rgba(180, 180, 180, 0.2)",
        },
        // 每个轴的样式
        itemStyle: {
          color: "#479AD3", // 设置柱子的颜色
          color: ({ value }) => (value < 25 ? "red" : "#479AD3"),
          barBorderRadius: 5, // 设置柱子的圆角
          shadowColor: "rgba(0, 0, 0, 0.3)", // 设置柱子的阴影颜色
          shadowBlur: 5, // 设置柱子的阴影模糊大小
        },
        // 轴宽度
        barWidth: 12,
        // 轴上的字体
        label: {
          show: true,
          // 设置标签位置为右侧
          position: "right",
          textStyle: {
            // 设置标签文本颜色
            color: "#fff",
          },
          //添加
          formatter: "{c}%",
        },
      },
    ],
    //超过80就变色
    // visualMap:{
    // 	show:false,
    // 	pieces:[
    // 		{
    // 			gt:80,color:'red'
    // 		},
    // 		{
    // 			lte:80,color:'#479AD3'
    // 		}
    // 	]
    // }
  };

  mChart.setOption(options);
};

// 监听数据的变化，重新渲染图表
watch(
  () => props.data,
  () => {
    renderChart();
  }
);

const dialogVisibleAdd = ref(false);
const dialogVisibleCorrect = ref(false);
const name = ref(props.data?.name || "");
const length = ref("");
const width = ref("");
const sheet = ref("");
const sheetRemind = ref("");

function showFormDialogAdd() {
  dialogVisibleAdd.value = true;
  name.value = props.data?.name || "";
}
function showFormDialogCorrect() {
  dialogVisibleCorrect.value = true;
  name.value = props.data?.name || "";
}

// 确认按钮处理
const confirm = () => {
  let content = "";
  // 构建显示内容
  if (dialogVisibleAdd.value === true) {
    content = `客户: ${name.value}<br/>幅宽: ${width.value}<br/>托数: ${length.value}<br/>每托张数：${sheet.value}`;
  } else if (dialogVisibleCorrect.value === true) {
    content += `客户: ${name.value}<br/>幅宽: ${width.value}<br/>剩余的完整托数: ${length.value}<br/>每托张数：${sheet.value}<br/>剩余的张数：${sheetRemind.value}`;
  }

  ElMessageBox({
    title: "确认",
    message: `请确认添加以下纸皮库存:<br/>${content}`,
    dangerouslyUseHTMLString: true, // 允许 message 中的 HTML
    confirmButtonText: "确定",
    cancelButtonText: "修改",
    type: "warning",
    showConfirmButton: true,
    showCancelButton: true,
  })
    .then(() => {
      if (dialogVisibleAdd.value === true) {
        submit();
      } else if (dialogVisibleCorrect.value === true) {
        submitCorrect();
      }
    })
    .catch(() => {
      console.log("用户点击取消按钮");
    });
};
const submit = async () => {
  // 获取输入值
  const nameValue = name.value;
  const widthValue = width.value;
  const lengthValue = length.value;
  const sheetValue = sheet.value;
  const customer = ref(localStorage.getItem("customer") || "");
  // 校验输入是否为空
  if (!nameValue || !widthValue || !lengthValue) {
    ElMessage.error("请输入所有必填项");
    return;
  }

  // 校验输入是否为数字
  if (isNaN(widthValue) || isNaN(lengthValue)) {
    ElMessage.error("幅宽和托数必须为数字");
    return;
  }
  try {
    const response = await resetStockTime2Api(
      nameValue,
      widthValue,
      lengthValue,
      sheetValue,
      customer.value
    );

    if (response && response.data && response.data.code === 200) {
      ElMessage.success("添加成功: " + response.data.message);
    } else {
      ElMessage.error("提交失败: " + (response?.data?.error || "操作未成功"));
    }
  } catch (error) {
    console.error("请求失败:", error);

    if (error.response) {
      // 后端返回的错误信息
      ElMessage.error("请求失败: " + error.response.data.message);
    } else if (error.message) {
      // 请求错误，但非后端返回，如网络错误
      ElMessage.error("请求失败: " + error.message);
    } else {
      // 其他错误
      ElMessage.error("请求失败");
    }
  }

  dialogVisibleAdd.value = false;
};
const submitCorrect = async () => {
  // 获取输入值
  const nameValue = name.value;
  const widthValue = width.value;
  const lengthValue = length.value;
  const sheetValue = sheet.value;
  const sheetRemindValue = sheetRemind.value;
  const customer = ref(localStorage.getItem("customer") || "");
  // 校验输入是否为空
  if (!nameValue || !widthValue || !lengthValue) {
    ElMessage.error("请输入所有必填项");
    return;
  }

  // 校验输入是否为数字
  if (isNaN(widthValue) || isNaN(lengthValue)) {
    ElMessage.error("幅宽和托数必须为数字");
    return;
  }
  try {
    const response = await CorrectStockApi(
      nameValue,
      widthValue,
      lengthValue,
      sheetValue,
      customer.value,
      sheetRemindValue
    );

    if (response && response.data && response.data.code === 200) {
      ElMessage.success("添加成功: " + response.data.message);
    } else {
      ElMessage.error("提交失败: " + (response?.data?.error || "操作未成功"));
    }
  } catch (error) {
    console.error("请求失败:", error);

    if (error.response) {
      // 后端返回的错误信息
      ElMessage.error("请求失败: " + error.response.data.message);
    } else if (error.message) {
      // 请求错误，但非后端返回，如网络错误
      ElMessage.error("请求失败: " + error.message);
    } else {
      // 其他错误
      ElMessage.error("请求失败");
    }
  }

  dialogVisibleCorrect.value = false;
};
</script>

<style lang="scss" scoped></style>

